using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using Core.Common;
using Core.Expansion;
using Core.Function;
using Newtonsoft.Json.Linq;
using Tool.Common;
using Tool.Expansion;
using Tool.Web.HttpHelper;
using Tool.Windows.Win32;
using static Core.Common.Global;

namespace Core.HandleMsg
{
	public static class General
	{
		#region 需要的函数和变量
		[DllImport("data\\app\\com.acgdmzy.acg\\dmzy.dll", CallingConvention = CallingConvention.StdCall)]
		private static extern string GetNewAnimeList(int DayOfWeek);

		[DllImport("data\\app\\com.acgdmzy.acg\\dmzy.dll", CallingConvention = CallingConvention.StdCall)]
		private static extern string GetHitokoto();

		[DllImport("data\\app\\com.acgdmzy.acg\\dmzy.dll", CallingConvention = CallingConvention.StdCall)]
		private static extern string GetAnimeIntroduction();

		[DllImport("data\\app\\com.acgdmzy.acg\\dmzy.dll", CallingConvention = CallingConvention.StdCall)]
		private static extern string BiliGetRank(int lx, int nr, int day);

		private static class _Reg
		{
			public static Regex BIliAvAndEp = new Regex("(av|ep)(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
			public static Regex BIliMdAndSs = new Regex("(md|ss)(\\d+)", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
			public static Regex BiliBv = new Regex("bv([\\w]{10})", RegexOptions.IgnoreCase | RegexOptions.Compiled | RegexOptions.Singleline);
		}
		#endregion

		public static int Handle(long qun, long qq, string msg)
		{
			if (Reg.Ascii2d.IsMatch(msg))
			{
				Match match = Reg.Ascii2d.Match(msg);
				if (!string.IsNullOrWhiteSpace(match.Groups[1].Value))
				{
					_A2d(qun, qq, match.Groups[1].Value);
				}
				else
				{
					if (msg.ToLower() != "a2d搜索")
					{
						return 0;
					}
					if (hashTable.Contains("a2d" + qq.ToString()))
					{
						hashTable["a2d" + qq.ToString()] = true;
					}
					else
					{
						hashTable.Add("a2d" + qq.ToString(), true);
					}
					CQ.SendGroupMessage(qun, "主人请发送一张想要搜索的图片噢(*′▽\uff40*)");
				}
				return 1;
			}
			else if (Reg.CQImg.IsMatch(msg) && ((bool?)hashTable.Read("a2d" + qq.ToString()) ?? false))
			{
				hashTable["a2d" + qq.ToString()] = false;
				Match match2 = Reg.CQImg.Match(msg);
				_A2d(qun, qq, match2.Groups[1].Value);
				return 1;
			}			
			else if (_Reg.BIliMdAndSs.IsMatch(msg) && !msg.Contains("监控") && Win32Help.IniReadValue(AppDir + "bilibili-通用.ini", "MD解析", "开关", "开", 65535) == "开")
			{
				Match match4 = _Reg.BIliMdAndSs.Match(msg);
				if (match4.Groups[1].Value.ToLower() == "md")
				{
					if (int.TryParse(match4.Groups[2].Value, out int result3))
					{
						CQ.SendGroupMessage(qun, BiliBili.MdParse(result3));
					}
				}
				else if (match4.Groups[1].Value.ToLower() == "ss" && int.TryParse(match4.Groups[2].Value, out int result4))
				{
					CQ.SendGroupMessage(qun, BiliBili.SsParse(result4));
				}
				return 1;
			}
			else if ((msg == "开b站解析" || msg == "开B站解析") && qq == Master)
			{
				Win32Help.IniWriteValue(AppDir + "bilibili-通用.ini", "AV解析", "开关", "开");
				CQ.SendGroupMessage(qun, "b站视频解析功能已经开启");
				return 1;
			}
			else if ((msg == "关b站解析" || msg == "关B站解析") && qq == Master)
			{
				Win32Help.IniWriteValue(AppDir + "bilibili-通用.ini", "AV解析", "开关", "关");
				CQ.SendGroupMessage(qun, "b站视频解析功能已经关闭");
				return 1;
			}
			else if (msg == "新番列表")
			{
				CQ.SendGroupMessage(qun, Anime.GetNewAnimeList2(DateTime.Now.DayOfWeek));
				return 1;
			}
			else if (msg == "明日新番列表")
			{
				CQ.SendGroupMessage(qun, Anime.GetNewAnimeList2(DateTime.Now.AddDays(1).DayOfWeek));
				return 1;
			}
			else if (msg == "昨日新番列表")
			{
				CQ.SendGroupMessage(qun, Anime.GetNewAnimeList2(DateTime.Now.AddDays(-1).DayOfWeek));
				return 1;
			}
			else if (msg == "一言" || msg == "宅语")
			{
				CQ.SendGroupMessage(qun,Other.GetHitokoto());
				return 1;
			}
			else if (msg == "今日新番介绍")
			{
				CQ.SendGroupMessage(qun, GetAnimeIntroduction().Trim(' ', '\r', '\n'));
				return 1;
			}
			else if (Reg.BiliRank.IsMatch(msg))
			{
				Match match5 = Reg.BiliRank.Match(msg);
				int lx = 0;
				int num = (!string.IsNullOrEmpty(match5.Groups[1].Value)) ? int.Parse(match5.Groups[1].Value) : int.Parse(Win32Help.IniReadValue(AppDir + "bilibili-通用.ini", "b站排行榜", "内容", "0", 65535));
				if (num < 0)
				{
					num = 0;
				}
				if (num > 15)
				{
					num = 15;
				}
				int day = (!string.IsNullOrEmpty(match5.Groups[2].Value)) ? int.Parse(match5.Groups[2].Value) : int.Parse(Win32Help.IniReadValue(AppDir + "bilibili-通用.ini", "b站排行榜", "日期", "2", 65535));
				CQ.SendGroupMessage(qun, BiliGetRank(lx, num, day));
				return 1;
			}
			else if (msg == "授权信息" && qq == Master)
			{
				try
				{
					JObject jObject = JObject.Parse(Encoding.UTF8.GetString(HttpNet.Get(Global.ServerAddressAuthorization + CQ.GetLoginQQ().ToString())));
					if (jObject.ContainsKey("dateTime"))
					{
						CQ.SendGroupMessage(qun, string.Format("授权状态：{0}\r\n授权号码：{1}\r\n到期时间：{2}", Global.Authorization ? "已授权" : "未授权", CQ.GetLoginQQ(), Global.DecryptString(jObject["dateTime"].ToString())));
					}
					else
					{
						CQ.SendGroupMessage(qun, "授权状态：" + (Global.Authorization ? "已授权" : "未授权"));
					}
				}
				catch (Exception ex)
				{
					CQ.SendGroupMessage(qun, "获取授权信息失败,失败信息:" + ex.Message);
				}
				return 1;
			}
			else if (msg.ToLower() == "随机cos")
			{
				CQ.SendGroupMessage(qun, Pixiv.GetRandCos());
				return 1;
			}
			//番剧搜索
			else if (Regex.IsMatch(msg, "^[0-9]{1,2}$"))
			{
				if (hashTable.Read("番剧搜索" + qq) is Anime.SearchResult result && result.ready && result.qq == qq)
				{
					var index = int.Parse(msg) - 1;
					if (index < 0 || index >= result.animeInfos.Count) return 1;
					CQ.SendGroupMessage(qun, CQ.Code_AT(qq) + result.animeInfos[index].name + Anime.GetWp(result.animeInfos[index].url));
					hashTable.Remove("番剧搜索" + qq);
					return 1;
				}
			}
			else if (!Reg.BiliGif.IsMatch(msg) && Win32Help.IniReadValue(AppDir + "bilibili-通用.ini", "AV解析", "开关", "开", 65535) == "开")
			{
				if (_Reg.BIliAvAndEp.IsMatch(msg))
				{
					Match match3 = _Reg.BIliAvAndEp.Match(msg);
					if (match3.Groups[1].Value.ToLower() == "av")
					{
						CQ.SendGroupMessage(qun, BiliBili.AvAndBvParse(match3.Groups[2].Value, 0));
					}
					else if (match3.Groups[1].Value.ToLower() == "ep" && int.TryParse(match3.Groups[2].Value, out int result))
					{
						CQ.SendGroupMessage(qun, BiliBili.EpParse(result));
					}
					return 1;
				}
				else if (_Reg.BiliBv.IsMatch(msg))
				{
					var match = _Reg.BiliBv.Match(msg);
					CQ.SendGroupMessage(qun, BiliBili.AvAndBvParse(match.Groups[1].Value, 1));
					return 1;
				}
			}
			return 0;
		}

		private static void _A2d(long Qun, long QQ, string file)
		{
			CQ.SendGroupMessage(Qun, WaitMessage);
			string imageurl = Win32Help.IniReadValue(AppDomain.CurrentDomain.BaseDirectory + "data\\image\\" + file + ".cqimg", "image", "url", null, 2048);
			if (A2d.Ascii2dSearch(imageurl, out Ascii2dSearchInfo searchresult))
			{
				string text = ImagePath + TimeHelp.GetCurrentTimeUnix(false).ToString() + ".jpg";
				File.WriteAllBytes(text, HttpNet.Get(searchresult.ImgUrl, null, null, null, 10000, Proxy, null, true, true));
				string text2 = CQ.Code_Image(text.HandleImagePath());
				if (!string.IsNullOrEmpty(searchresult.Source))
				{
					text2 = text2 + "\r\n" + searchresult.Source + "：" + searchresult.Url;
				}
				if (!string.IsNullOrEmpty(searchresult.Author))
				{
					text2 = text2 + "\r\nAuthor：" + searchresult.Author;
				}
				text2 = text2 + "\r\n详细信息：" + searchresult.ResultUrl;
				CQ.SendGroupMessage(Qun, CQ.Code_AT(QQ) + "这是色合検索到的结果\r\n" + text2);
			}
			if (A2d.Ascii2dSearch(imageurl, out Ascii2dSearchInfo searchresult2, isbovw: true))
			{
				string text3 = ImagePath + TimeHelp.GetCurrentTimeUnix(false).ToString() + ".jpg";
				File.WriteAllBytes(text3, HttpNet.Get(searchresult2.ImgUrl, null, null, null, 10000, Proxy, null, true, true));
				string text4 = CQ.Code_Image(text3.HandleImagePath());
				if (!string.IsNullOrEmpty(searchresult2.Source))
				{
					text4 = text4 + "\r\n" + searchresult2.Source + "：" + searchresult2.Url;
				}
				if (!string.IsNullOrEmpty(searchresult2.Author))
				{
					text4 = text4 + "\r\nAuthor：" + searchresult2.Author;
				}
				text4 = text4 + "\r\n详细信息：" + searchresult2.ResultUrl;
				CQ.SendGroupMessage(Qun, CQ.Code_AT(QQ) + "这是特徴検索到的结果\r\n" + text4);
			}
		}
	}
}
